package com.itheima.web;

import com.itheima.pojo.NewShoppingCart;
import com.itheima.pojo.User;
import com.itheima.service.NewShoppingCartService;
import com.itheima.service.ShoppingCartService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/newDeleteShoppingCartGoodsServlet")
public class NewDeleteShoppingCartGoodsServlet extends HttpServlet {
    private NewShoppingCartService service = new NewShoppingCartService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 通过session获取user对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();

        Integer itemId = Integer.valueOf(request.getParameter("id"));

        service.delete(itemId, userId);

        // 判断购物车中是否有两个及以上的小米手机，生成赠品
        List<NewShoppingCart> xiaomiPhones = service.selectByBuyerIdAndItemId(3, userId);
        if (!xiaomiPhones.isEmpty()) {
            Integer itemQuantity = xiaomiPhones.get(0).getItemQuantity();
            Integer giftQuantity = itemQuantity / 2;
            if (giftQuantity > 0) {
                List<NewShoppingCart> gifts = service.selectByBuyerIdAndItemId(8, userId);
                // 如果购物车中还没有赠品
                if (gifts.isEmpty()) {
                    service.add(8, userId, giftQuantity);
                }
                // 如果购物车中已经有赠品
                else {
                    service.updateItemQuantity(8, userId, giftQuantity);
                }
            }
        }
        // 没有购买小米手机
        else {
            service.delete(8, userId);
        }

        response.sendRedirect("newShoppingCartSelectServlet");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
